﻿@using Newtonsoft.Json
@using Entity
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增仓库</title>
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- Element Plus资源 -->
    <link href="https://unpkg.com/element-plus/dist/index.css" rel="stylesheet" />
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>

    <style>
        /* 样式保持不变 */
        .container {
            width: 95%;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 16px;
        }

        .note-input {
            height: 100px;
        }

        .table-operation {
            margin-bottom: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .btn-group {
            display: flex;
            gap: 8px;
        }

        .pagination-container {
            margin-top: 16px;
            text-align: right;
        }

        .empty-tip {
            text-align: center;
            padding: 50px 0;
            color: #999;
        }

        .dialog-form {
            padding: 20px 0;
        }

        .dialog-footer {
            text-align: right;
            padding-top: 20px;
            border-top: 1px solid #ebeef5;
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <!-- 基础信息表单 -->
        <div class="form-group">
            <h3>基础信息</h3>
            <el-form :model="form" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库编号" required class="form-item">
                            <el-input v-model="form.warehouseNumber" placeholder="自动生成中..." readonly :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="仓库名称" required class="form-item">
                            <el-input v-model="form.warehouseName" placeholder="请输入仓库名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库容量/m³" required class="form-item">
                            <el-input v-model.number="form.warehouseCapacity" type="number" min="0" step="1" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库管部门" required class="form-item">
                            <el-select v-model="form.orgId" placeholder="请选择" clearable>
                                <el-option v-for="org in organizations" :key="org.organization_id" :label="org.organization_name" :value="org.organization_id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库主管" required class="form-item">
                            <el-select v-model="form.managerId" placeholder="请选择" clearable @@change="handleManagerChange">
                                <el-option v-for="user in warehouseManagers" :key="user.UserId" :label="user.UserName" :value="user.UserId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" class="form-item">
                            <el-input v-model="form.phone" placeholder="请选择仓库主管自动获取" maxlength="11" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库地址" class="form-item">
                            <el-input v-model="form.warehouseAddress" placeholder="请输入仓库详细地址"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="默认仓库" class="form-item">
                            <el-checkbox v-model="form.isDefault">设为默认仓库</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="排序" class="form-item">
                            <el-input v-model.number="form.sorting" type="number" min="0" placeholder="0"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="仓库状态" required class="form-item">
                            <el-radio-group v-model="form.status">
                                <el-radio :label="1">启用</el-radio>
                                <el-radio :label="0">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="仓库锁定" class="form-item">
                            <el-switch v-model="form.locked" :active-value="1" :inactive-value="0" active-text="锁定" inactive-text="未锁定"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="form.note" type="textarea" placeholder="请输入" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 库位信息表格 -->
        <div class="form-group">
            <div class="table-operation">
                <h3>库位信息</h3>
                <div class="btn-group">
                    <el-button type="primary" size="small" @@click="addLocation">新增</el-button>
                    <el-button type="primary" size="small" @@click="fetchLocationData">刷新</el-button>
                </div>
            </div>

            <el-table :data="paginationResult.data" border ref="locationTable" @@selection-change="handleLocationSelectionChange" v-loading="loading">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" type="index" width="60"></el-table-column>
                <el-table-column prop="location_number" label="库位编号" align="center"></el-table-column>
                <el-table-column prop="location_name" label="库位名称" align="center"></el-table-column>
                <el-table-column prop="storage_location_capacity" label="库位容量/m³" align="center"></el-table-column>
                <el-table-column label="库位主管" align="center">
                    <template #default="scope">{{ getUserName(scope.row.users_id) }}</template>
                </el-table-column>
                <el-table-column prop="sorting" label="排序" align="center"></el-table-column>
                <el-table-column prop="location_status" label="状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.location_status === 1 ? 'success' : 'danger'">
                            {{ scope.row.location_status === 1 ? '启用' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="note" label="备注"></el-table-column>
                <el-table-column label="操作" width="80">
                    <template #default="scope">
                        <el-button type="text" size="small" @@click="deleteLocation(scope.row)" style="color: #ff4d4f;">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="empty-tip" v-if="!loading && paginationResult.data.length === 0">
                <p>暂无库位数据</p>
            </div>

            <div class="pagination-container" v-if="paginationResult.totalCount > 0">
                <el-pagination v-model:current-page="paginationQuery.pageIndex" v-model:page-size="paginationQuery.pageSize"
                               :page-sizes="[5, 10, 20, 50]" :total="paginationResult.totalCount"
                               layout="total, sizes, prev, pager, next, jumper"
                               @@size-change="handlePageSizeChange" @@current-change="handleCurrentPageChange"></el-pagination>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px; text-align: center;">
            <el-button @@click="goBack">关闭</el-button>
            <el-button type="primary" @@click="saveAndAdd">保存并新增</el-button>
            <el-button type="primary" @@click="save">保存</el-button>
        </div>

        <!-- 库位对话框 -->
        <el-dialog v-model="locationDialogVisible" title="新增库位" width="600px" align-center>
            <el-form :model="locationForm" label-width="100px" class="dialog-form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="库位编号" required class="form-item">
                            <el-input v-model="locationForm.locationNumber" placeholder="自动生成中..." readonly :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库位名称" required class="form-item">
                            <el-input v-model="locationForm.locationName" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="库位容量" required class="form-item">
                            <el-input v-model.number="locationForm.storageLocationCapacity" type="number" min="0" step="1" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库位主管" required class="form-item">
                            <el-select v-model="locationForm.usersId" placeholder="请选择" clearable>
                                <el-option v-for="user in warehouseManagers" :key="user.UserId" :label="user.UserName" :value="user.UserId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="排序" class="form-item">
                            <el-input v-model.number="locationForm.sorting" type="number" min="0" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库位状态" required class="form-item">
                            <el-radio-group v-model="locationForm.locationStatus">
                                <el-radio :label="1">启用</el-radio>
                                <el-radio :label="0">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="locationForm.note" type="textarea" placeholder="请输入" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @@click="locationDialogVisible = false">取消</el-button>
                    <el-button type="primary" @@click="submitLocationForm" :loading="submitting">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <script>
        const serverData = {
            organizations: @Html.Raw(JsonConvert.SerializeObject(ViewBag.Organizations ?? new List<SysOrgOrganizations>())),
            warehouseManagers: @Html.Raw(JsonConvert.SerializeObject(ViewBag.WarehouseManagers ?? new List<SysOrgUserManagement>()))
        };

        const { createApp, ref, reactive, onMounted } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            setup() {
                // 状态变量
                const loading = ref(false);
                const submitting = ref(false);
                const locationDialogVisible = ref(false);

                // 仓库表单数据
                const form = reactive({
                    warehouseNumber: '',
                    warehouseName: '',
                    warehouseCapacity: null,
                    orgId: null,
                    managerId: null,
                    phone: '',
                    warehouseAddress: '',
                    isDefault: false,
                    sorting: 0,
                    status: 1,
                    locked: 0,
                    note: ''
                });

                // 库位表单数据
                const locationForm = reactive({
                    locationNumber: '',
                    locationName: '',
                    storageLocationCapacity: null,
                    usersId: null,
                    sorting: 0,
                    locationStatus: 1,
                    note: ''
                });

                // 数据
                const organizations = reactive(Array.isArray(serverData.organizations) ? serverData.organizations : []);
                const warehouseManagers = reactive(Array.isArray(serverData.warehouseManagers) ? serverData.warehouseManagers : []);

                // 分页相关
                const paginationQuery = reactive({
                    pageIndex: 1,
                    pageSize: 5
                });

                const paginationResult = reactive({
                    data: [],
                    totalCount: 0,
                    totalPages: 0,
                    pageIndex: 1,
                    pageSize: 5
                });

                const selectedLocationIds = ref([]);
                const locationTable = ref(null);

                // 获取用户名
                const getUserName = (userId) => {
                    if (!userId || userId === 0) return '无';
                    const user = warehouseManagers.find(item => item.UserId === userId);
                    return user?.UserName ? user.UserName : `[未知用户:${userId}]`;
                };

                // 仓库主管选择变化时自动填充电话
                const handleManagerChange = (managerId) => {
                    form.phone = '';
                    if (!managerId) return;

                    const selectedManager = warehouseManagers.find(user => user.UserId === managerId);
                    if (selectedManager) {
                        form.phone = selectedManager.PhoneNumber || selectedManager.phone || selectedManager.mobile || '';
                    }
                };

                // 生成仓库编号 - 使用 rule_id=13（对应target_id=20）
                const generateWarehouseNumber = async () => {
                    try {
                        console.log("开始生成仓库编号，使用rule_id=13");
                        const response = await axios.post(
                            '/NumberingRule/GenerateBusinessNumber',
                            { rule_id: 13 },  // 使用 rule_id=13，它对应 target_id=20
                            { headers: { 'Content-Type': 'application/json' }, timeout: 10000 }
                        );
                        if (response.data.success) {
                            form.warehouseNumber = response.data.businessNumber;
                            console.log("仓库编号生成成功:", form.warehouseNumber);
                        } else {
                            ElMessage.error(`仓库编号生成失败：${response.data.message || '未知错误'}`);
                            form.warehouseNumber = '';
                        }
                    } catch (error) {
                        console.error("生成仓库编号异常:", error);
                        ElMessage.error('网络异常，无法生成仓库编号');
                        form.warehouseNumber = '';
                    }
                };

                // 生成库位编号 - 使用 rule_id=14（对应target_id=21）
                const generateLocationNumber = async () => {
                    try {
                        console.log("开始生成库位编号，使用rule_id=14");
                        const response = await axios.post(
                            '/NumberingRule/GenerateBusinessNumber',
                            { rule_id: 14 },  // 使用 rule_id=14，它对应 target_id=21
                            { headers: { 'Content-Type': 'application/json' } }
                        );
                        if (response.data.success) {
                            locationForm.locationNumber = response.data.businessNumber;
                            console.log("库位编号生成成功:", locationForm.locationNumber);
                        } else {
                            ElMessage.error(`库位编号生成失败：${response.data.message || '未知错误'}`);
                            locationForm.locationNumber = '';
                        }
                    } catch (error) {
                        console.error("生成库位编号异常:", error);
                        ElMessage.error('网络异常，无法生成库位编号，请重试');
                        locationForm.locationNumber = '';
                    }
                };

                // 加载库位数据
                const fetchLocationData = async () => {
                    loading.value = true;
                    try {
                        const response = await axios.get('/Warehouse/GetStorageLocationPagedList', { params: paginationQuery });
                        if (response.data.code === 200) {
                            const resData = response.data.data || {};
                            paginationResult.data = Array.isArray(resData.data) ? resData.data : [];
                            paginationResult.totalCount = Number(resData.totalCount) || 0;
                            paginationResult.totalPages = Number(resData.totalPages) || 0;
                            paginationResult.pageIndex = Number(resData.pageIndex) || 1;
                            paginationResult.pageSize = Number(resData.pageSize) || 5;
                        } else {
                            ElMessage.error(response.data.message || '库位查询失败');
                            paginationResult.data = [];
                            paginationResult.totalCount = 0;
                        }
                    } catch (error) {
                        ElMessage.error('网络异常，无法加载库位');
                        paginationResult.data = [];
                        paginationResult.totalCount = 0;
                    } finally {
                        loading.value = false;
                    }
                };

                // 处理选择
                const handleLocationSelectionChange = (selection) => {
                    const safeSelection = Array.isArray(selection) ? selection : [];
                    selectedLocationIds.value = safeSelection.map(item => item.location_id).filter(id => id != null);
                };

                // 分页事件
                const handlePageSizeChange = (size) => {
                    paginationQuery.pageSize = size;
                    paginationQuery.pageIndex = 1;
                    fetchLocationData();
                };

                const handleCurrentPageChange = (page) => {
                    paginationQuery.pageIndex = page;
                    fetchLocationData();
                };

                // 新增库位
                const addLocation = () => {
                    Object.assign(locationForm, {
                        locationNumber: '',
                        locationName: '',
                        storageLocationCapacity: null,
                        usersId: null,
                        sorting: 0,
                        locationStatus: 1,
                        note: ''
                    });
                    generateLocationNumber();
                    locationDialogVisible.value = true;
                };

                // 提交库位表单
                const submitLocationForm = async () => {
                    if (!locationForm.locationNumber.trim()) {
                        ElMessage.warning('库位编号生成失败，请稍后重试');
                        return;
                    }
                    if (!locationForm.locationName.trim()) {
                        ElMessage.warning('请输入库位名称');
                        return;
                    }
                    if (locationForm.storageLocationCapacity == null || locationForm.storageLocationCapacity <= 0) {
                        ElMessage.warning('请输入有效的库位容量（大于0）');
                        return;
                    }
                    if (!locationForm.usersId) {
                        ElMessage.warning('请选择库位主管');
                        return;
                    }

                    submitting.value = true;
                    try {
                        const requestData = {
                            LocationNumber: locationForm.locationNumber,
                            LocationName: locationForm.locationName,
                            LocationCapacity: locationForm.storageLocationCapacity,
                            LocationManager: locationForm.usersId,
                            LocationSorting: locationForm.sorting,
                            LocationStatus: locationForm.locationStatus,
                            LocationNote: locationForm.note || null
                        };
                        const response = await axios.post('/Warehouse/AddStorageLocation', requestData);
                        if (response.data.code === 200) {
                            ElMessage.success('新增库位成功');
                            locationDialogVisible.value = false;
                            fetchLocationData();
                        } else {
                            ElMessage.error(response.data.message || '新增库位失败');
                        }
                    } catch (error) {
                        ElMessage.error('网络异常，新增库位失败');
                    } finally {
                        submitting.value = false;
                    }
                };

                // 删除库位
                const deleteLocation = (row) => {
                    if (!row?.location_id) return;
                    ElMessageBox.confirm(
                        `确定删除库位"${row.location_name}"？删除后不可恢复`,
                        '确认删除',
                        { type: 'warning' }
                    ).then(async () => {
                        try {
                            const response = await axios.post(`/Warehouse/DeleteStorageLocation?id=${row.location_id}`);
                            if (response.data.code === 200) {
                                ElMessage.success('删除成功');
                                fetchLocationData();
                            } else {
                                ElMessage.error(response.data.message || '删除失败');
                            }
                        } catch (error) {
                            ElMessage.error('网络异常，删除失败');
                        }
                    });
                };

                // 提交仓库表单
                const submitForm = async (isContinue) => {
                    if (!form.warehouseNumber.trim()) {
                        ElMessage.warning('仓库编号生成失败，请稍后重试');
                        return;
                    }
                    if (!form.warehouseName.trim()) {
                        ElMessage.warning('请输入仓库名称');
                        return;
                    }
                    if (form.warehouseCapacity == null || form.warehouseCapacity <= 0) {
                        ElMessage.warning('请输入有效的仓库容量（大于0）');
                        return;
                    }
                    if (!form.orgId) {
                        ElMessage.warning('请选择库管部门');
                        return;
                    }
                    if (!form.managerId) {
                        ElMessage.warning('请选择仓库主管');
                        return;
                    }
                    if (selectedLocationIds.value.length === 0) {
                        ElMessage.warning('请至少选择一个关联的库位');
                        return;
                    }

                    try {
                        const requestData = {
                            WarehouseNumber: form.warehouseNumber,
                            WarehouseName: form.warehouseName,
                            WarehouseCapacity: form.warehouseCapacity,
                            OrgId: form.orgId,
                            ManagerId: form.managerId,
                            Phone: form.phone || null,
                            Address: form.warehouseAddress || null,
                            IsDefault: form.isDefault,
                            Sorting: form.sorting,
                            Status: form.status,
                            Locked: form.locked,
                            Note: form.note || null,
                            SelectedLocationIds: selectedLocationIds.value
                        };
                        const response = await axios.post('/Warehouse/Add', requestData, {
                            timeout: 30000,
                            headers: { 'Content-Type': 'application/json' }
                        });
                        if (response.data.code === 200) {
                            ElMessage.success('仓库新增成功');
                            if (isContinue) {
                                Object.keys(form).forEach(key => {
                                    form[key] = key === 'status' ? 1 : (key === 'sorting' ? 0 : (key === 'isDefault' ? false : (key === 'locked' ? 0 : '')));
                                });
                                form.warehouseCapacity = null;
                                form.orgId = null;
                                form.managerId = null;
                                form.phone = '';
                                selectedLocationIds.value = [];
                                locationTable.value?.clearSelection();
                                generateWarehouseNumber();
                            } else {
                                window.location.href = '/Warehouse/Index';
                            }
                        } else {
                            ElMessage.error(response.data.message || '新增仓库失败');
                        }
                    } catch (error) {
                        if (error.response) {
                            ElMessage.error(`服务器错误 (${error.response.status}): ${error.response.data?.message || error.message}`);
                        } else if (error.request) {
                            ElMessage.error('网络连接错误，请检查网络连接或服务器状态');
                        } else {
                            ElMessage.error(`请求配置错误: ${error.message}`);
                        }
                    }
                };

                // 其他方法
                const goBack = () => window.history.back();
                const save = () => submitForm(false);
                const saveAndAdd = () => submitForm(true);

                // 初始化
                onMounted(() => {
                    fetchLocationData();
                    generateWarehouseNumber();
                });

                return {
                    form, locationForm, organizations, warehouseManagers,
                    paginationQuery, paginationResult, loading, submitting,
                    locationTable, selectedLocationIds, locationDialogVisible,
                    getUserName, fetchLocationData, handleLocationSelectionChange,
                    handlePageSizeChange, handleCurrentPageChange, addLocation,
                    submitLocationForm, deleteLocation, goBack, save, saveAndAdd,
                    handleManagerChange
                };
            }
        })
        .use(ElementPlus)
        .mount('#app');
    </script>
</body>
</html>